import $common from '@/utils/common.js'
let reConnectionTimer = null

export default {
  star (obj) {
    const _this = this
    console.log(' ')
    console.log('star11---obj ', obj)
    if (reConnectionTimer) {
      clearInterval(reConnectionTimer)
      reConnectionTimer = null
    }
    // debugger
    const socket = new WebSocket('ws://localhost:8081/ws')

    // WebSocket已连接
    socket.onopen = function (event) {
      console.log('WebSocket已连接')
      socket.dispatch({
        ...obj,
        msg: 'Hello, server!'
      })
      if (reConnectionTimer) {
        clearInterval(reConnectionTimer)
        reConnectionTimer = null
      }
    }

    // 接受WebSocket发来的消息
    socket.onmessage = function (event) {
      const data = JSON.parse(event.data)
      console.log('收到服务器消息:', data)
      const type = data.type
      switch (type) {
        case 1:
          console.clear()
          break
        case 2:
          location.reload()
          break
        default:
          break
      }
    }

    // WebSocket已关闭
    socket.onclose = function (event) {
      console.log('WebSocket已关闭')
      reConnectionTimer = setTimeout(() => {
        // console.log('0.尝试重新连接')
        _this.star()
      }, 1500)
    }

    // WebSocket出错
    socket.onerror = function (error) {
      console.error('WebSocket出错:', error)
    }

    socket.dispatch = function (data) {
      // debugger
      data.uuid = $common.getSession('uuid')
      // if (data.type === 1) debugger
      socket.send(JSON.stringify(data))
    }
    return socket
  }
}

// // 将创建的signal赋值给Vue实例
// export default {
//   // install方法的第一个参数是 Vue 构造器，第二个参数是一个可选的选项对象。
//   install: function (Vue, options) {
//     Vue.prototype.$socket = socket
//   }
// }
